package com.change.service.friends;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.change.core.page.Page;
import com.change.dto.req.QueryFriendsReq;
import com.change.dto.req.SaveFriendsReq;
import com.change.dto.resp.QueryFriendsResp;
import com.change.entity.friends.Friends;
import com.change.mapper.friends.FriendsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author 坏孩子是你啊
* @date  2022-08-18
*/
@Slf4j
@Service
public class FriendsService extends ServiceImpl<FriendsMapper, Friends>{
    private final FriendsMapper friendsMapper;

    public FriendsService(FriendsMapper friendsMapper) {
    this.friendsMapper = friendsMapper;
    }

    public Page<List<QueryFriendsResp>> getPage(Page page, QueryFriendsReq req) {
        page.offset();
        List<QueryFriendsResp> records = this.friendsMapper.pageFriends(page, req);
        page.setRecords(records);
        long total = this.friendsMapper.pageFriendsTotal(req);
        page.setTotal(total);
        return page;
    }

    public QueryFriendsResp detail(Integer id) {
        Friends friends = this.friendsMapper.selectById(id);
        QueryFriendsResp friendsResp = new QueryFriendsResp();
        BeanUtil.copyProperties(friends, friendsResp);
        return friendsResp;
    }

    @Transactional(rollbackFor = Exception.class)
    public Friends save(SaveFriendsReq req) {
        Friends friends = new Friends();
        // 如果用户微信号以 wxid_ 开头，设置该用户备注和微信号一致
        if (req.getWxNo().startsWith("wxid_")) {
            friends.setRemarks(req.getWxNo());
        }
        BeanUtil.copyProperties(req, friends);
        this.friendsMapper.insert(friends);
        return friends;
    }

    @Transactional(rollbackFor = Exception.class)
    public Friends update(SaveFriendsReq req) {
        Friends friends = this.friendsMapper.selectById(req.getId());
        BeanUtil.copyProperties(req, friends);
        friendsMapper.updateById(friends);
        return friends;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer delete(Integer id) {
        Friends friends = this.friendsMapper.selectById(id);
        friends.setDeleted(1);
        return this.friendsMapper.updateById(friends);
    }
}
